#ifndef PriorityQueue_h
#define PriorityQueue_h

#include <vector>

namespace yfy {
template<class T>
class Less
{
public:
    bool operator()(const T& a, const T& b)
    {
        return a < b;
    }
};

template<class T>
class Greater
{
public:
    bool operator()(const T& a, const T& b)
    {
        return a > b;
    }
};

template<class T, class Container = vector<T>, class Compare = Less<T>>
class priority_queue
{
public:
    priority_queue()
    {}
    
    template <class InputIterator>
    priority_queue(InputIterator first, InputIterator last)
    {
        //插入数据
        while(first != last)
        {
            _con.push_back(*first);
            first++;
        }
        //建堆
        for(size_t i = (_con.size() - 1 - 1) / 2; i >= 0; i--)
        {
            AdjustDown(i);
        }
    }
    
    Compare com;
    void AdjustUp(size_t child)
    {
        size_t parent = (child - 1) / 2;
        while(child > 0)
        {
            if(com(_con[parent], _con[child]))
            {
                swap(_con[parent], _con[child]);
                child = parent;
                parent = (child - 1) / 2;
            }
            else
            {
                break;
            }
        }
    }
    
    void AdjustDown(size_t parent)
    {
        size_t l_child = parent * 2 + 1;
        while(l_child < _con.size())
        {
            if(l_child + 1 < _con.size() && com(_con[l_child], _con[l_child + 1]))
            {
                l_child++;
            }
            if(com(_con[parent], _con[l_child]))
            {
                swap(_con[parent], _con[l_child]);
                parent = l_child;
                l_child = parent * 2 + 1;
            }
            else
            {
                break;
            }
        }
        
    }
    
    void push(const T& val)
    {
        _con.push_back(val);
        AdjustUp(_con.size() - 1);
    }
    
    void pop()
    {
        swap(_con[0], _con[_con.size() - 1]);
        _con.pop_back();
        AdjustDown(0);
    }
    
    const T& top()
    {
        return _con.front();
    }
    
    bool empty()
    {
        return _con.empty();
    }
    
private:
    Container _con;
};

void test1()
{
    priority_queue<int, vector<int>, Greater<int>> pq;
    pq.push(1);
    pq.push(0);
    pq.push(3);
    pq.push(100);
    
    while(!pq.empty())
    {
        cout << pq.top() << endl;
        pq.pop();
    }
}

}

#endif /* PriorityQueue_h */
